package com.etocrm.saas.lib.base.feign.codec.decode;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.Decoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * saas 通用feign decoder
 * Created by Xs on 2022/11/24.
 */
@Slf4j
public class SaasFeignDecoder implements Decoder {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public Object decode(Response response, Type type) throws IOException, FeignException {
        String jsonStr = Util.toString(response.body().asReader(Util.UTF_8));
        try {
            return objectMapper.readValue(jsonStr, new TypeReference<Type>() {
                @Override
                public Type getType() {
                    return type;
                }
            });
        } catch (Exception e) {
            log.error("feign jackson decode error... " + e.getMessage(), e);
            return JSONUtil.toBean(jsonStr, type, true);
        }
    }
}


